package cn.phecda.boot.tenant.data.configuration;

import cn.phecda.boot.tenant.core.annotation.ConditionalOnTableStrategy;
import cn.phecda.boot.tenant.core.annotation.ConditionalOnTenantEnabled;
import cn.phecda.boot.tenant.data.jpa.TenantCurrentIdentifierResolver;
import cn.phecda.boot.tenant.data.mybatis.DefaultTenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p> 租户数据配置 </p>
 *
 * @author : wanpinwei
 */
@Slf4j
@ConditionalOnTenantEnabled
@Configuration(proxyBeanMethods = false)
public class TenantDataConfiguration {

    @PostConstruct
    public void postConstruct() {
        log.info("|Phecda Boot Tenant|- Tenant Data Configuration");
    }

    @ConditionalOnTableStrategy
    @Configuration(proxyBeanMethods = false)
    public static class TenantTableStrategyConfiguration {
        @PostConstruct
        public void postConstruct() {
            log.info("|Phecda Boot Tenant|- Tenant Table Strategy Configuration");
        }

        @Bean
        public TenantCurrentIdentifierResolver tenantCurrentIdentifierResolver() {
            TenantCurrentIdentifierResolver resolver = new TenantCurrentIdentifierResolver();
            log.trace("|Phecda Boot Tenant|- Tenant Current Identifier Resolver");
            return resolver;
        }

        @Bean
        @ConditionalOnBean(MybatisPlusInterceptor.class)
        public DefaultTenantLineHandler defaultTenantLineHandler(MybatisPlusInterceptor interceptor) {
            DefaultTenantLineHandler handler = new DefaultTenantLineHandler();
            TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor();
            tenantLineInnerInterceptor.setTenantLineHandler(handler);
            interceptor.addInnerInterceptor(tenantLineInnerInterceptor);
            log.trace("|Phecda Boot Tenant|- Default Tenant Line Handler");
            return handler;
        }

    }

}
